package org.geektimes.web.mvc.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.eclipse.microprofile.config.Config;
import org.geektimes.configuration.microprofile.config.ConfigHolder;
import org.geektimes.web.mvc.initializer.MyWebConfigurationApplicationInitializer;

public class AddConfigFilter implements Filter {
	
	private ServletContext servletContext;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.servletContext = filterConfig.getServletContext();
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		Config config = (Config)servletContext.getAttribute(MyWebConfigurationApplicationInitializer.CONFIG_NAME);
		if( config != null ) {
			ConfigHolder.set(config);
		}
		try{
			chain.doFilter(request, response);
		}finally {
			ConfigHolder.remove();
		}
		
	}

	@Override
	public void destroy() {

	}

}
